package com.lpgu.scan;

import com.lpgu.repositories.CustomerRepository;
import com.lpgu.repositories.MyJpaRepository;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;

/**
 * @author: lpgu
 * @describe:JpaFactoryBean
 * @createAt: 2022/1/6 9:44
 * FactoryBean是一个特殊bean，拥有自己的属性
 */
//@Component
public class JpaFactoryBean implements FactoryBean {

    @Autowired
    private LocalContainerEntityManagerFactoryBean entityManagerFactoryBean;
    private Class<?> repositoryInterface;

    public JpaFactoryBean(Class<?> repositoryInterface) {
        this.repositoryInterface = repositoryInterface;
    }

    //随意控制实例化过程
    @Override
    public Object getObject() throws Exception {
        EntityManager entityManager = entityManagerFactoryBean.createNativeEntityManager(null);

        //获取pojo类，
        // getGenericInterfaces()拿到当前的父接口
        ParameterizedType genericInterfaces =(ParameterizedType) repositoryInterface.getGenericInterfaces()[0];
        //拿到接口的泛型<Customer, Long>
        Type actualTypeArgument = genericInterfaces.getActualTypeArguments()[0];
        Class clazz =Class.forName(actualTypeArgument.getTypeName());
        System.out.println("==============init factorybean generator bean");
      return Proxy.newProxyInstance(repositoryInterface.getClassLoader(),
                new Class[]{repositoryInterface}, new MyJpaRepository(entityManager,clazz));
    }

    //返回对象的类型
    @Override
    public Class<?> getObjectType() {
        return repositoryInterface;
    }
}
